package com.erclab.internal.xpresso.formelements;

import java.util.Properties;

import org.apache.log4j.Logger;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.exceptions.FormException;
import com.erclab.internal.xpresso.forms.Form;
import com.xpresso.utils.exceptions.XpressoException;
import com.xpresso.utils.image.ThumbnailCreator;
import com.xpresso.utils.props.PropertyWorker;

public class XUpload extends FormElement {

	private static final Logger log = Logger.getLogger(XUpload.class);
	
	@Override
	public boolean isModifiable() {
		return true;
	}

	@Override
	public void loadLookupValues(Form theForm) throws FormException {
		// Not necessary

	}

	@Override
	public String toHTML(Form theForm) {
		Properties props = getProperties();
		StringBuffer sb = new StringBuffer();
		sb.append("<script src=\""+ props.getProperty("XUpload.js.path") + "\"></script>\n");
		sb.append("<script>var winWidth=" + props.getProperty("XUpload.win.width") + ";\n");
		sb.append("var winHeight=" + props.getProperty("XUpload.win.height") + ";\n</script>\n");
		sb.append("<INPUT TYPE=\"hidden\" name=\"Field");
		sb.append(this.idFormElement);
		sb.append("\"");
		sb.append(" id=\"UploadField" + this.destinationColumn + "\" ");
		if (theForm.getFormParameters().getAction().equals("update")
				&& originalValue != null && !originalValue.equals("")){
			sb.append("value=\"" + originalValue + "\">");
			sb.append("<span class=\"XUpload\" id=\"UploadSpan" + this.destinationColumn + "\"><br>\n");
			sb.append(getFilePreview(originalValue));
			sb.append("<a href=\"javascript:uploadFile('" + this.destinationColumn + "')\"><br>\n" + 
					props.getProperty("XUpload.text.changeFile") + "</a></span>");
			sb.append(getThumbnailData(props));
		} else {		
			sb.append("><span class=\"XUpload\" id=\"UploadSpan" + this.destinationColumn + "\">\n" +
					"<a href=\"javascript:uploadFile('" + this.destinationColumn + "')\">" + 
					props.getProperty("XUpload.text.selectFile") + "</a></span>");
			sb.append(getThumbnailData(props));
		}
		return sb.toString();

	}
	
	protected String getThumbnailData(Properties props) {
		String createThumbnail = props.getProperty("XUpload.createThumbnail");		
		if (createThumbnail != null && createThumbnail.equals("true")){
			StringBuffer sb = new StringBuffer();
			sb.append("<input type=\"hidden\" value=\"" + props.getProperty("XUpload.Thumbnail.width"));
			sb.append("\" id=\"width" + this.destinationColumn + "\">");
			sb.append("<input type=\"hidden\" value=\"" + props.getProperty("XUpload.Thumbnail.height"));
			sb.append("\" id=\"height" + this.destinationColumn + "\">");
			sb.append("<input type=\"hidden\" value=\"" + props.getProperty("XUpload.Thumbnail.quality"));
			sb.append("\" id=\"quality" + this.destinationColumn + "\">");
			return sb.toString();
		} else {
			return "";
		}
	}

	protected String getFilePreview(String originalValue) {
		// Create a preview of the file dpending on the extension:
		String extension = getExtension(originalValue);
		log.info("File extension: " + extension);
		StringBuffer sb = new StringBuffer();
		sb.append("<a href=\"javascript:openMediaWindow('" + originalValue + "')\">");
		if (extension != null){
			if (extension.toUpperCase().equals(".GIF") || extension.toUpperCase().equals(".JPG")){
				Properties props = getProperties();
				String createThumbnail = props.getProperty("XUpload.createThumbnail");
				if (createThumbnail != null && createThumbnail.equals("true")){
					//int tWidth = Integer.parseInt(props.getProperty("XUpload.Thumbnail.width"));
					//int tHeight = Integer.parseInt(props.getProperty("XUpload.Thumbnail.height"));
					//sb.append("<img src=\"" +  originalValue + "\" border=0 width=\"" + tWidth +
					//	"\" height=\"" + tHeight + "\">");
					sb.append("<img src=\"" +  originalValue + "\" border=0>");			
				} else {
					sb.append("<img src=\"" +  originalValue + "\" border=0>");
				}
			} else if (extension.toUpperCase().equals(".SWF") || extension.toUpperCase().equals(".FLV")){
				sb.append("<img src=\"../html/images/FlashMovie.gif\" border=0>");
			}
		} else {
			return "?";
		}
		sb.append("</a>");
		return sb.toString();
		
	}

	private String getExtension(String originalValue) {
		if (originalValue != null && !originalValue.equals("")){
			String extension = originalValue.substring(originalValue.length() - 4, originalValue.length());
			return extension;
		} else {
			return null;
		}
	}

	@Override
	public boolean isHidden(){
		return false;
	}
	
	@Override
	public String[] processSubmittedValues(Form theForm, String[] submittedValues) {
		log.info("Processing image submitted. Submitted value: " + submittedValues[0]);
		Properties props = getProperties();
		String createThumbnail = props.getProperty("XUpload.createThumbnail");
		String extension = getExtension(submittedValues[0]);
		if (createThumbnail(submittedValues, createThumbnail)){
			int tWidth = Integer.parseInt(props.getProperty("XUpload.Thumbnail.width"));
			int tHeight = Integer.parseInt(props.getProperty("XUpload.Thumbnail.height"));
			int quality = Integer.parseInt(props.getProperty("XUpload.Thumbnail.quality"));
			log.info("Info to create thumbnail. W: " + tWidth + " H:" + tHeight + " Q:" + quality + " F: " + submittedValues[0]);
			String fullPath = getFullPath(submittedValues[0]);
			log.info("Full Path to image: " + fullPath);
			try {
				ThumbnailCreator.createImageThumbnail(fullPath, tWidth, tHeight, fullPath + ".thumb" + extension, quality);
			} catch (XpressoException e) {
				log.error("An error occurred creating thumbnail: " + e.getDescription());
				log.error(e.getTheException());
			}
			
			if (submittedValues[0] != null){
				return new String[]{submittedValues[0] + ".thumb" + extension};
			}
		} 
		return submittedValues;
	}

	private boolean createThumbnail(String[] submittedValues, String createThumbnail) {
		return createThumbnail != null 
				&& createThumbnail.equals("true")
				&& submittedValues != null 
				&& submittedValues[0] != null 
				&& ! submittedValues[0].equals("")
				&& ! (submittedValues[0].indexOf("thumb") > 0);
	}

	protected String getFullPath(String fileName) {
		String absolutePath = Settings.getProperty("application.absolute.path");
		fileName = fileName.substring(3, fileName.length());		
		return absolutePath + fileName;
	}

	private Properties getProperties() {
		Properties props = new PropertyWorker().getProperties(this.parameters);
		return props;
	}

}
